package com.seeqool.v1;

import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.swing.ImageIcon;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeExpansionEvent;
import javax.swing.event.TreeWillExpandListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.ExpandVetoException;
import javax.swing.tree.TreePath;

public class DatabaseBrowser extends JScrollPane implements TreeWillExpandListener {

	private static final long serialVersionUID = 1L;
	
	private static DatabaseMetaData dbMetaData = null;
	
	private static DefaultMutableTreeNode dbBrowser = new DefaultMutableTreeNode("not connected");
	private static JTree dbTree = new JTree(dbBrowser);
	
	
	public DatabaseBrowser() {
		super();
		ImageIcon[] icons = {ImageLibrary.get("database.png"), 
				             ImageLibrary.get("table.png"),
				             ImageLibrary.get("column.png")};
		dbTree.setCellRenderer(new DatabaseTreeCellRenderer(icons));
		dbTree.addTreeWillExpandListener(this);
		this.setViewportView(dbTree);
	}
	
	public static void browse(String url, String username, String password) throws SQLException {
		dbMetaData = DriverManager.getConnection(url, username, password).getMetaData();
		ResultSet result=dbMetaData.getTables(null, null, "%", null);
		while (result.next()) {
			if (!result.getString(4).equals("SYSTEM TABLE")) {
				dbBrowser.setUserObject(result.getString(1));
				DefaultMutableTreeNode node = new DefaultMutableTreeNode(result.getString(3), true);
				node.add(new DefaultMutableTreeNode("loading...", false));
				dbBrowser.add(node);
			}
		}
		dbTree.expandPath(new TreePath(dbBrowser.getRoot()));
	}

	public void treeWillCollapse(TreeExpansionEvent e) throws ExpandVetoException {}

	public void treeWillExpand(TreeExpansionEvent e) throws ExpandVetoException {
		if (e.getPath().getPathCount()==2) {
			DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.getPath().getLastPathComponent();
			if ((node.getChildCount()==1) && node.getChildAt(0).toString().equals("loading...")) {
				try {
					ResultSet result = dbMetaData.getColumns(null, null, node.getUserObject().toString(), null);
					boolean isFirst = true;
					while (result.next()) {
						if (isFirst) {
							((DefaultMutableTreeNode) node.getChildAt(0)).setUserObject(result.getString("COLUMN_NAME"));
							isFirst=false;
						} else {
							node.add(new DefaultMutableTreeNode(result.getString("COLUMN_NAME"), false));
						}
					}
				} catch (SQLException e1) {
					e1.printStackTrace();
				}
			}
		}
	}
}
